interface Storage {
  get(key: string): any
  set(key: string, value: any): void
  remove(key: string): void
  clear(): void
}

/**
 * localStorage 操作工具类
 */
class LocalStorage implements Storage {
  /**
   * 获取存储的值
   * @param key 键名
   * @returns 解析后的值
   */
  get(key: string): any {
    const value = window.localStorage.getItem(key);
    try {
      return value ? JSON.parse(value) : null;
    } catch (error) {
      return value;
    }
  }

  /**
   * 设置存储的值
   * @param key 键名
   * @param value 值
   */
  set(key: string, value: any): void {
    if (value === undefined) {
      return;
    }
    const data = JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  /**
   * 移除指定的存储项
   * @param key 键名
   */
  remove(key: string): void {
    window.localStorage.removeItem(key);
  }

  /**
   * 清空所有存储
   */
  clear(): void {
    window.localStorage.clear();
  }

  /**
   * 获取所有存储的键名
   * @returns 键名数组
   */
  keys(): string[] {
    return Object.keys(window.localStorage);
  }

  /**
   * 判断是否存在某个键
   * @param key 键名
   * @returns boolean
   */
  has(key: string): boolean {
    return window.localStorage.getItem(key) !== null;
  }

  /**
   * 获取存储数量
   * @returns number
   */
  size(): number {
    return window.localStorage.length;
  }
}

// 创建实例
const storage = new LocalStorage();

// 导出实例
export default storage;
